import React from "react";

import {getTheme} from "../../theme";
import {inject, observer} from "mobx-react";
import {action, observable, toJS} from "mobx";
import ThemeHeaderSetting from "./theme/Header";

import defaultTheme from "../../theme/styles/default";
import Directive from "../../component/base/directive";
import page from "../../../../../apis/page";
import ThemeFormSetting from "./theme/Form";
import ThemeTitleSetting from "./theme/Title";
import ThemeFieldSetting from "./theme/Field";
import ThemeBackgroundSetting from "./theme/Background";
import "./theme/index.less";
import ThemeSubmitBtnSetting from "./theme/SubmitBtn";

const themes = [
  {type:'default',img:'/edc/images/theme/icon/default.jpeg'},
  //{type:'light',img:'/edc/images/theme/icon/light.jpeg'},
  {type:'anthony',img:'/edc/images/theme/icon/anthony.jpg'},
  {type:'red',img:'/edc/images/theme/icon/red.png'},
  //{type:'green',img:'/edc/images/theme/icon/green.png'},
  //{type:'brown',img:'/edc/images/theme/icon/brown.jpeg'},
  //{type:'grey',img:'/edc/images/theme/icon/grey.jpeg'}
  {type:'pawel',img:'/edc/images/theme/icon/pawel.jpg'},
  {type:'bravo',img:'/edc/images/theme/icon/bravo.jpg'},
  {type:'zanon',img:'/edc/images/theme/icon/zanon.jpg'}

];

@inject('edcFormDesignerStore')
@observer
export default class ThemePane extends React.Component {
  @observable active = null;
  @observable custom = defaultTheme;

  constructor(props) {
    super();

    this.store = props.edcFormDesignerStore;
    this.onThemeChange = this.onThemeChange.bind(this);
    this.handlePropChange = this.handlePropChange.bind(this);
    this.uploadImg = this.uploadImg.bind(this);
    this.handlePropSet = this.handlePropSet.bind(this);

    const {theme} = this.store;
    if(theme){
      this.custom = theme;
      this.onThemeChange();
    }
  }

  handlePropChange(key, handleValue = v => v, debounceTime) {
    const directive = new Directive(key, this);

    if(_.isNumber(handleValue)) {
      debounceTime = handleValue;
      handleValue = v => v;
    }

    const handleChange = value => {
      value = directive.with(value, handleValue);

      if( value.color){
        value = value.color;
      }

      this.onPropsChange(directive.realKey, value);
      // 联动属性
      directive.refs.forEach(({key, value}) => {
        this.onPropsChange(key, value);
      });
    };

    if (debounceTime) {
      return _.debounce(handleChange, debounceTime);
    }
    return handleChange;
  }


  handlePropSet(key, value) {
    const directive = new Directive(key, this);

    const handleChange = value => {
      this.onPropsChange(directive.realKey, value);
      // 联动属性
      directive.refs.forEach(({key, value}) => {
        this.onPropsChange(key, value);
      });
    };
    return handleChange(value);
  }

  onPropsChange(key, value) {
    const keys = key.split('.'); // 针对复杂的子对象 如:a.b
    const _setValue = obj => {
      const len = keys.length;
      keys.reduce((prev, key, index) => {
        if(len !== index + 1) return prev[key];
        prev[key] = value;
      }, obj);
    };
    _setValue(this.custom);
    this.custom = toJS(this.custom);

    if(key.indexOf('border') != -1){
      const{border} = this.custom.form;
      const{color, width} = border;

      border.css = {
        border: 'solid '+ color + " " + width + "px"
      };
    }else if(key.indexOf('background.repeat') != -1){
      const{background} = this.custom;
      background.css.backgroundRepeat = value == '0' ? 'no-repeat' : 'repeat';
      background.css.backgroundSize = value == '0' ? 'cover' : 'inherit';
    }else if(key.indexOf('background.type') != -1){
      const{background} = this.custom;

      if(value == '1'){
        let img = background.css.backgroundImage;
        background.image = img;
        background.css.backgroundImage = '';
      }else{
        background.image && (background.css.backgroundImage = background.image);
        background.css.backgroundPosition = 'top center';
        background.image = null;
      }
    }else if(key.indexOf('submitBtn.css.backgroundColor') != -1){
      const{submitBtn} = this.custom;
      submitBtn.css.borderColor = value;
    }else if(key.indexOf('form.shadow') != -1){
      const{form} = this.custom;
      if(value){
        form.css.WebkitBoxShadow = '0 3px 5px rgba(0,0,0,0.15)';
        form.css.boxShadow = '0 3px 5px rgba(0,0,0,0.15)';
      }else{
        form.css.WebkitBoxShadow = '';
        form.css.boxShadow = '';
      }
    }
    this.onThemeChange();
  }

  onThemeChange(type) {
    const {custom} = this;
    const { onThemeChange } = this.store;
    if(!type){
      onThemeChange(toJS(custom));
      return;
    }

    const theme = getTheme(type);
    this.active = type;
    this.custom = theme;
    onThemeChange(theme);
  }


  uploadImg(e){
    const{_targetInst} = e;
    const {key} = _targetInst;
    const value = e.target.value;
    if(value){
      const data = new FormData();
      data.append('image',e.target.files[0]);
      page.uploadImg(data).then(res => {
        let url = key.indexOf('header') != -1 ? res.image : "url(" + res.image + ")";
        this.handlePropSet(key, url);
      });
    }
  }

  render() {
    const {active,custom} = this;
    const {background,form,header,title,field, submitBtn} = custom;
    return (
      <div className='edc-theme-pane'>
        <div className={'edc-theme-templates'}>
        <div className="edc-theme-inner">
        {
          themes.map(({type,img}) => {
            return (
              (active && type == active) ?
                <div className="edc-theme-item active" onClick={() => {this.onThemeChange(type)}}><img src={img}/></div>
                :
                <div className="edc-theme-item" onClick={() => {this.onThemeChange(type)}}><img src={img}/></div>
            )
          })
        }
        </div>
      </div>

        <div className='edc-theme-settings'>
          <ThemeBackgroundSetting onChange={this.handlePropChange} onUploadImg={this.uploadImg} data={background}/>
          <ThemeFormSetting onChange={this.handlePropChange} data={form}/>
          <ThemeHeaderSetting onChange={this.handlePropChange} onUploadImg={this.uploadImg} data={header} />
          <ThemeTitleSetting onChange={this.handlePropChange} data={title} />
          <ThemeFieldSetting onChange={this.handlePropChange} data={field} />
          <ThemeSubmitBtnSetting onChange={this.handlePropChange} data={submitBtn}/>
        </div>
      </div>
    );
  }
}